<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>自定义指令</title>
</head>

<body>
  <div id="root">
    <!-- v-red 自定义指令 -->
    <div v-red>你好世界</div>
    <div v-color="'blue'">你好世界</div>
    <div v-color1="color">你好世界</div>
    <input type="text" v-model='color'>

    <hr>
    <!-- 输入框中的内容长度大于5位，就提示 -->
    <input type="text" v-model='title' v-vlen="5">
    <hr>
    <!-- 打开页面时，让光标聚焦到指定的输入框中 -->
    <input type="text" v-focus>
  </div>
  <script src="./js/vue.js"></script>
  <script>
    // 定义全局的自定义指令
    Vue.directive('red', {
      // bind inserted update
      // el当前使用指令的dom对象
      // bindings 指令获取修饰符，值,获取对象
      bind(el, bindings) {
        // console.log(el)
        // console.log(bindings)
        el.style.color = 'red'
      },
    })

    Vue.directive('color2', (el, bindings) => { })

    const vm = new Vue({
      el: '#root',
      data: {
        color: 'red',
        title: 'aa'
      },
      // 局部定义指令 this指向不是Vue对象，不能使用this 指令操作dom对象
      directives: {
        color: {
          bind(el, bindings) {
            el.style.color = bindings.value
          }
        },
        /* color1:{
          bind(el, bindings) {
            el.style.color = bindings.value
          },
          update(el, bindings) {
            el.style.color = bindings.value
          }
        } */
        // 简写方式，触发 bind和update 钩子函数
        color1(el, bindings) {
          el.style.color = bindings.value
        },
        // bind update
        vlen(el, bindings) {
          console.log(bindings)
          // 转为数字
          let len = bindings.value * 1
          if (el.value.length > len) {
            el.style.color = 'red'
          }else{
            el.style.color = 'black'
          }
        },
        focus:{
          inserted(el,bindings){
            // 此时元素已经在dom中
            el.focus()
          }
        }
      }
    })
  </script>
</body>

</html>